package com.zhu.edu.shiro;

import com.zhu.edu.entity.Role;
import com.zhu.edu.entity.User;
import com.zhu.edu.service.PermissionService;
import com.zhu.edu.service.RoleService;
import com.zhu.edu.service.UserService;
import com.zhu.edu.token.JwtToken;
import com.zhu.edu.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 自定义realm 将认证授权数据的来源转为数据库的实现
 */
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @Override
    //使用自定义的token
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) principalCollection.iterator().next();
        // 获取角色
        Set<String> roles = roleService.getRolesByUserName(userName);
        // 获取权限
        Set<String> permissions = permissionService.getPermissionsByUsername(userName);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
       // 获取身份信息
        String token = (String) jwtToken.getPrincipal();
        // 解析
        Claims claims = JwtUtil.parseJWT(token);
        // 获取username
        String username = claims.getId();
        User user = userService.getUserByUsername(username);
        if (user == null){
            return null;
        }
        return new SimpleAuthenticationInfo(username, user.getPassword(), getName());
    }
}